﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using noteVt.Models.DataModels;

namespace noteVt.Validators
{
    public class UniqueArticleAliasAttribute : ValidationAttribute
    {
        private readonly MainContext _dbContext = new MainContext();
        
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var article = validationContext.ObjectInstance as Article;
            if (article != null && (value == null || article.Id != Guid.Empty))
            {
                return ValidationResult.Success;
            }
            Guid parseGuid;
            if (Guid.TryParse((string) value, out parseGuid))
            {
                return new ValidationResult(ErrorMessage);
            }
            int count = _dbContext.Articles.Count(a => a.Alias == (string) value);
            return count == 0 ? ValidationResult.Success : new ValidationResult(ErrorMessage);
        }
    }
}